package com.qifan.energy.global;

import android.app.ActivityManager;
import android.content.Context;

import androidx.annotation.NonNull;

import com.bumptech.glide.GlideBuilder;
import com.bumptech.glide.annotation.GlideModule;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.load.engine.bitmap_recycle.LruBitmapPool;
import com.bumptech.glide.load.engine.cache.DiskLruCacheFactory;
import com.bumptech.glide.load.engine.cache.ExternalPreferredCacheDiskCacheFactory;
import com.bumptech.glide.load.engine.cache.LruResourceCache;
import com.bumptech.glide.load.engine.cache.MemorySizeCalculator;
import com.bumptech.glide.module.AppGlideModule;
import com.bumptech.glide.request.RequestOptions;

import java.io.File;

/**
 * glide app 兼容
 *
 * @author xuan
 * @date 2018/3/27.
 */
@GlideModule
public final class MyGlideAppModule extends AppGlideModule {

    @Override
    public void applyOptions(@NonNull Context context, @NonNull GlideBuilder builder) {
        super.applyOptions(context, builder);
        MemorySizeCalculator calculator = new MemorySizeCalculator.Builder(context).setMemoryCacheScreens(2f).build();
        int defaultMemoryCacheSize = calculator.getMemoryCacheSize();
        int defaultBitmapPoolSize = calculator.getBitmapPoolSize();

        int memory = getAvailMemory(context);
        double value = 1.2;
        if (memory < 650) value = 1.0;
        if (memory < 350) value = 0.8;
        if (memory < 150) value = 0.5;

        long customMemoryCacheSize = (long) (defaultMemoryCacheSize * value);
        long customBitmapPoolSize = (long) (defaultBitmapPoolSize * value);

        //展开透明通道，之前为rgb565 透明色没有
        builder.setDefaultRequestOptions(new RequestOptions().format(DecodeFormat.PREFER_ARGB_8888));
        builder.setMemoryCache(new LruResourceCache(customMemoryCacheSize));
        builder.setBitmapPool(new LruBitmapPool(customBitmapPoolSize));

        File cacheDir = context.getExternalCacheDir();//指定的是数据的缓存地址
        int diskCacheSize = 1024 * 1024 * 500;//最多可以缓存多少字节的数据，这里是500M
        if (cacheDir == null) {
            builder.setDiskCache(new ExternalPreferredCacheDiskCacheFactory(context, "glide", diskCacheSize));
        } else {
            builder.setDiskCache(new DiskLruCacheFactory(cacheDir.getPath(), "glide", (long) diskCacheSize));
        }

        //加入这两行几乎不进行文件缓存，全被清完了
        /*val space = availableSpace()
        if (space < 80) {
            ThreadUtils.execute(Runnable { Glide.get(context).clearDiskCache() })
        }*/
    }

    private int getAvailMemory(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
        am.getMemoryInfo(memoryInfo);
        return (int) memoryInfo.availMem / (1024 * 1024);
    }
}
